# -*- coding: utf-8 -*-
# @Time:2021/08/03 23:43
# @Author:Cindy
from flask import request
from flask_restful import Resource
from models.testcases import TestCase
from server import db, app
import json


class TestCaseService(Resource):

    def get(self):
        # app.logger.warning('get success')
        # return {'error': 0, 'msg': 'get success'}
        case_id = request.args.get('id')
        if case_id:
            # 查询单条数据信息
            case_data = TestCase.query.filter_by(id=case_id).first()
            app.logger.info(case_data)
            data = [case_data.as_dict()]
        else:
            # 查询所有数据信息
            case_data = TestCase.query.all()
            data = [i.as_dict() for i in case_data]
        return {'error': 0, 'msg': {'data': data}}

    def post(self):
        # 增加一条案例
        case_data = request.json
        app.logger.info(case_data)
        # 从接口拿到的字典数据进行解包
        testcase = TestCase(**case_data)
        # 如果数据字段存在列表，需要进一步转换
        testcase.nodeid = json.dumps(request.json.get('nodeid'))
        db.session.add(testcase)
        db.session.commit()
        return {'error': 0, 'msg': 'post success'}

    def put(self):
        # 修改接口信息
        # 获取要修改的接口信息
        app.logger.info(request.json)
        case_id = request.json.get("id")
        case = TestCase.query.filter_by(id=case_id).\
            update(request.json)
        db.session.commit()
        app.logger.info(f'数据已修改，id{case_id}被修改为{request.json}')
        return {'error': 0, 'msg': {'id': case}}

    def delete(self):
        app.logger.info(request.args)
        case_id = request.args.get("id")
        if not case_id:
            return {'error': 40001, 'msg': 'delete case_id can not be null!'}
        case = TestCase.query.filter_by(id=case_id).delete()
        db.session.commit()
        app.logger.info(f'id{case_id}已删除')
        return {'error': 0, 'msg': 'delete success'}